/*
 * @lc app=leetcode.cn id=71 lang=cpp
 *
 * [71] 简化路径
 */

// @lc code=start
class Solution
{
public:
    string simplifyPath(string path)
    {
        vector<string> v;
        string s;
        for (int i = 0; i < path.size(); i++)
        {
            if (path[i] == '/')
            {
                if (s.size() > 0)
                {
                    v.push_back(s);
                    s = "";
                }
            }
            else
            {
                s += path[i];
            }
        }
        if (s.size() > 0)
        {
            v.push_back(s);
        }
        if (v.size() == 0)
        {
            return "/";
        }

        stack<string> stk;
        for (int i = 0; i < v.size(); i++)
        {
            if (v[i] == ".")
            {
                continue;
            }
            else if (v[i] == "..")
            {
                if (!stk.empty())
                {
                    stk.pop();
                }
            }
            else
            {
                stk.push(v[i]);
            }
        }

        string res;
        while (!stk.empty())
        {
            res = "/" + stk.top() + res;
            stk.pop();
        }
        return res.empty() ? "/" : res;
    }
};
// @lc code=end
